package com.jilintongyi.jlcrtvu.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jilintongyi.jlcrtvu.entity.SysLog;
import com.jilintongyi.jlcrtvu.service.LogService;
import com.jilintongyi.jlcrtvu.service.UserService;
import com.jilintongyi.jlcrtvu.util.HttpUtils;

/**
 * 登出成功处理
 */
@Component
public class LogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
	@Autowired
	LogService logService;

	@Autowired
	UserService userService;

	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		SysLog log = new SysLog();
		log.setUser(userService.findByUsername(authentication.getName()));
		ObjectMapper objectMapper = new ObjectMapper();
		log.setContent("登出成功 " +
				objectMapper.writeValueAsString(request.getParameterMap()));
		log.setIp(HttpUtils.getIpAddress(request));
		logService.save(log);
		// 成功跳转
		setDefaultTargetUrl("/login?logout");
		super.onLogoutSuccess(request, response, authentication);
	}
}
